<template>
  <div class="ai-chat-widget">
    <!-- 悬浮按钮 -->
    <div 
      v-show="!chatVisible"
      class="chat-button" 
      :style="buttonPosition"
      @mousedown="startDrag"
      @click="openChat">
      <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="badge">
        <el-icon :size="28" class="chat-icon">
          <ChatDotRound />
        </el-icon>
      </el-badge>
      <div class="button-text">AI客服</div>
    </div>

    <!-- 聊天窗口 -->
    <transition name="chat-slide">
      <div v-show="chatVisible" class="chat-window" :style="windowPosition">
        <!-- 标题栏 -->
        <div class="chat-header" @mousedown="startDragWindow">
          <div class="header-left">
            <el-icon :size="20" class="header-icon">
              <Service />
            </el-icon>
            <span class="header-title">AI智能客服</span>
          </div>
          <div class="header-actions">
            <el-icon :size="18" class="action-icon" @click="minimizeChat">
              <Minus />
            </el-icon>
            <el-icon :size="18" class="action-icon" @click="closeChat">
              <Close />
            </el-icon>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="chat-messages" ref="messagesContainer">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <el-icon :size="48" class="welcome-icon">
              <ChatDotRound />
            </el-icon>
            <div class="welcome-title">您好！我是AI智能客服</div>
            <div class="welcome-subtitle">有什么可以帮助您的吗？</div>
          </div>

          <!-- 对话消息 -->
          <div 
            v-for="(msg, index) in messages" 
            :key="index" 
            :class="['message-item', msg.role === 'user' ? 'user-message' : 'assistant-message']">
            <div class="message-avatar">
              <el-icon :size="24">
                <User v-if="msg.role === 'user'" />
                <Service v-else />
              </el-icon>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.content)"></div>
              <div class="message-time">{{ msg.timestamp }}</div>
            </div>
          </div>

          <!-- 加载动画 -->
          <div v-if="isLoading" class="message-item assistant-message">
            <div class="message-avatar">
              <el-icon :size="24">
                <Service />
              </el-icon>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="chat-input-area">
          <el-input
            v-model="inputMessage"
            :placeholder="isLoading ? '正在思考中...' : '输入消息...'"
            :disabled="isLoading"
            @keyup.enter="sendMessage"
            class="chat-input"
          >
            <template #append>
              <el-button 
                :icon="Position" 
                :loading="isLoading"
                @click="sendMessage"
                type="primary">
                发送
              </el-button>
            </template>
          </el-input>
        </div>

        <!-- 快捷问题 -->
        <div class="quick-questions" v-if="messages.length === 0">
          <div class="quick-title">常见问题：</div>
          <el-button 
            v-for="(question, index) in quickQuestions" 
            :key="index"
            size="small"
            class="quick-button"
            @click="sendQuickQuestion(question)">
            {{ question }}
          </el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, getCurrentInstance } from 'vue';
import { ChatDotRound, Service, User, Close, Minus, Position } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// 聊天窗口状态
const chatVisible = ref(false);
const inputMessage = ref('');
const messages = ref([]);
const isLoading = ref(false);
const unreadCount = ref(0);

// 悬浮按钮位置（可拖动）
const buttonPos = ref({ x: window.innerWidth - 100, y: window.innerHeight - 100 });
const isDragging = ref(false);
const dragStart = ref({ x: 0, y: 0 });

// 聊天窗口位置（可拖动）
const windowPos = ref({ x: window.innerWidth - 420, y: window.innerHeight - 600 });
const isDraggingWindow = ref(false);
const dragWindowStart = ref({ x: 0, y: 0 });

// 消息容器引用
const messagesContainer = ref(null);

// 快捷问题
const quickQuestions = ref([
  '如何查询库存？',
  '如何创建订单？',
  '如何进行出库操作？',
  '系统有哪些功能？'
]);

// 计算位置样式
const buttonPosition = computed(() => ({
  left: `${buttonPos.value.x}px`,
  top: `${buttonPos.value.y}px`
}));

const windowPosition = computed(() => ({
  left: `${windowPos.value.x}px`,
  top: `${windowPos.value.y}px`
}));

// 打开聊天窗口
const openChat = () => {
  if (isDragging.value) return; // 拖动时不打开
  chatVisible.value = true;
  unreadCount.value = 0;
  scrollToBottom();
};

// 关闭聊天窗口
const closeChat = () => {
  chatVisible.value = false;
};

// 最小化聊天窗口
const minimizeChat = () => {
  chatVisible.value = false;
};

// 开始拖动按钮
const startDrag = (e) => {
  if (e.button !== 0) return; // 只响应左键
  isDragging.value = true;
  dragStart.value = {
    x: e.clientX - buttonPos.value.x,
    y: e.clientY - buttonPos.value.y
  };

  const onMouseMove = (e) => {
    if (!isDragging.value) return;
    
    const newX = e.clientX - dragStart.value.x;
    const newY = e.clientY - dragStart.value.y;
    
    // 限制在窗口范围内
    buttonPos.value = {
      x: Math.max(0, Math.min(window.innerWidth - 80, newX)),
      y: Math.max(0, Math.min(window.innerHeight - 80, newY))
    };
  };

  const onMouseUp = () => {
    setTimeout(() => {
      isDragging.value = false;
    }, 100);
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
  };

  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
  e.preventDefault();
};

// 开始拖动窗口
const startDragWindow = (e) => {
  if (e.button !== 0) return;
  isDraggingWindow.value = true;
  dragWindowStart.value = {
    x: e.clientX - windowPos.value.x,
    y: e.clientY - windowPos.value.y
  };

  const onMouseMove = (e) => {
    if (!isDraggingWindow.value) return;
    
    const newX = e.clientX - dragWindowStart.value.x;
    const newY = e.clientY - dragWindowStart.value.y;
    
    windowPos.value = {
      x: Math.max(0, Math.min(window.innerWidth - 400, newX)),
      y: Math.max(0, Math.min(window.innerHeight - 560, newY))
    };
  };

  const onMouseUp = () => {
    isDraggingWindow.value = false;
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
  };

  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
  e.preventDefault();
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;

  // 添加用户消息
  addMessage('user', message);
  inputMessage.value = '';

  // 显示加载状态
  isLoading.value = true;
  scrollToBottom();

  try {
    // 准备对话历史
    const history = messages.value.slice(0, -1).map(msg => ({
      role: msg.role,
      content: msg.content
    }));

    // 调用后端API
    const response = await fetch(proxy.http.ipAddress + 'api/AICustomerService/Chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: message,
        history: history
      })
    });

    if (!response.ok) {
      throw new Error('网络请求失败');
    }

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let assistantMessage = '';
    let messageIndex = -1;

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');

      for (const line of lines) {
        if (!line.trim() || !line.startsWith('data:')) continue;

        const data = line.substring(5).trim();
        if (data === '[DONE]') break;

        try {
          const json = JSON.parse(data);
          
          // 检查是否有错误
          if (json.error) {
            throw new Error(json.message);
          }

          // 提取内容
          const content = json.choices?.[0]?.delta?.content;
          if (content) {
            assistantMessage += content;
            
            // 更新或添加助手消息
            if (messageIndex === -1) {
              messageIndex = messages.value.length;
              addMessage('assistant', assistantMessage);
            } else {
              messages.value[messageIndex].content = assistantMessage;
            }
            
            scrollToBottom();
          }
        } catch (e) {
          console.warn('解析消息失败:', e);
        }
      }
    }

    isLoading.value = false;
    scrollToBottom();

  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送失败: ' + error.message);
    addMessage('assistant', '抱歉，我遇到了一些问题，请稍后再试。');
    isLoading.value = false;
  }
};

// 发送快捷问题
const sendQuickQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

// 添加消息
const addMessage = (role, content) => {
  const timestamp = new Date().toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
  
  messages.value.push({
    role,
    content,
    timestamp
  });

  if (role === 'assistant' && !chatVisible.value) {
    unreadCount.value++;
  }

  nextTick(() => scrollToBottom());
};

// 格式化消息（支持简单的Markdown）
const formatMessage = (text) => {
  if (!text) return '';
  
  // 转义HTML
  text = text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  
  // 支持换行
  text = text.replace(/\n/g, '<br>');
  
  // 支持粗体 **text**
  text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 支持代码 `code`
  text = text.replace(/`(.*?)`/g, '<code>$1</code>');
  
  return text;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 暴露方法（可选）
defineExpose({
  openChat,
  closeChat
});
</script>

<style scoped lang="less">
.ai-chat-widget {
  position: fixed;
  z-index: 9999;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 悬浮按钮 */
.chat-button {
  position: fixed;
  width: 70px;
  height: 70px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  user-select: none;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
  }

  &:active {
    transform: scale(0.95);
  }

  .chat-icon {
    color: #fff;
    margin-bottom: 2px;
  }

  .button-text {
    color: #fff;
    font-size: 11px;
    font-weight: 500;
    margin-top: 2px;
  }

  .badge {
    :deep(.el-badge__content) {
      background-color: #f56c6c;
      border: 2px solid #fff;
    }
  }
}

/* 聊天窗口 */
.chat-window {
  position: fixed;
  width: 400px;
  height: 560px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 标题栏 */
.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
  user-select: none;

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;

    .header-icon {
      color: #fff;
    }

    .header-title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .header-actions {
    display: flex;
    gap: 10px;

    .action-icon {
      color: #fff;
      cursor: pointer;
      padding: 4px;
      border-radius: 4px;
      transition: background 0.2s;

      &:hover {
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }
}

/* 消息列表 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }
}

/* 欢迎消息 */
.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;

  .welcome-icon {
    color: #667eea;
    margin-bottom: 16px;
  }

  .welcome-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .welcome-subtitle {
    font-size: 14px;
    color: #909399;
  }
}

/* 消息项 */
.message-item {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease;

  .message-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: #e4e7ed;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-right: 12px;

    .el-icon {
      color: #606266;
    }
  }

  .message-content {
    flex: 1;
    max-width: calc(100% - 48px);
  }

  .message-text {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    line-height: 1.6;
    word-wrap: break-word;
    font-size: 14px;
    color: #303133;

    :deep(code) {
      background: #f4f4f5;
      padding: 2px 6px;
      border-radius: 3px;
      font-family: 'Courier New', monospace;
      font-size: 13px;
    }

    :deep(strong) {
      font-weight: 600;
      color: #409eff;
    }
  }

  .message-time {
    margin-top: 6px;
    font-size: 12px;
    color: #c0c4cc;
    padding-left: 16px;
  }
}

.user-message {
  flex-direction: row-reverse;

  .message-avatar {
    margin-right: 0;
    margin-left: 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

    .el-icon {
      color: #fff;
    }
  }

  .message-text {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;

    :deep(code) {
      background: rgba(255, 255, 255, 0.2);
      color: #fff;
    }

    :deep(strong) {
      color: #fff;
    }
  }

  .message-time {
    text-align: right;
    padding-left: 0;
    padding-right: 16px;
  }
}

.assistant-message {
  .message-avatar {
    background: #f0f0ff;

    .el-icon {
      color: #667eea;
    }
  }
}

/* 加载动画 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;

  span {
    width: 8px;
    height: 8px;
    background: #c0c4cc;
    border-radius: 50%;
    animation: typing 1.4s infinite;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 输入区域 */
.chat-input-area {
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #e4e7ed;

  .chat-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
    }

    :deep(.el-input-group__append) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;

      .el-button {
        background: transparent;
        border: none;
        color: #fff;
        font-weight: 500;

        &:hover {
          background: rgba(255, 255, 255, 0.1);
        }
      }
    }
  }
}

/* 快捷问题 */
.quick-questions {
  padding: 12px 20px;
  background: #fff;
  border-top: 1px solid #e4e7ed;

  .quick-title {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
  }

  .quick-button {
    margin-right: 8px;
    margin-bottom: 8px;
    border-radius: 16px;
    font-size: 12px;
  }
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-slide-enter-active,
.chat-slide-leave-active {
  transition: all 0.3s ease;
}

.chat-slide-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.9);
}

.chat-slide-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.9);
}
</style>

